import os
import json
import yaml
from datetime import datetime

class CommonUtils:
    @staticmethod
    def read_yaml_file(file_path):
        """
        读取YAML配置文件
        """
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        except Exception as e:
            raise Exception(f"读取YAML文件失败: {e}")
    
    @staticmethod
    def write_json_file(file_path, data):
        """
        写入JSON文件
        """
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(file_path), exist_ok=True)
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
        except Exception as e:
            raise Exception(f"写入JSON文件失败: {e}")
    
    @staticmethod
    def read_json_file(file_path):
        """
        读取JSON文件
        """
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            return None
        except Exception as e:
            raise Exception(f"读取JSON文件失败: {e}")
    
    @staticmethod
    def write_text_file(file_path, content):
        """
        写入文本文件
        """
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(file_path), exist_ok=True)
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
        except Exception as e:
            raise Exception(f"写入文本文件失败: {e}")
    
    @staticmethod
    def ensure_directory_exists(directory_path):
        """
        确保目录存在
        """
        if not os.path.exists(directory_path):
            os.makedirs(directory_path)
    
    @staticmethod
    def convert_case_to_lower(case_str):
        """
        将字符串转换为小写
        """
        if case_str:
            return case_str.lower()
        return case_str
    
    @staticmethod
    def get_current_timestamp():
        """
        获取当前时间戳
        """
        return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    @staticmethod
    def calculate_time_cost(start_time):
        """
        计算耗时
        """
        end_time = datetime.now()
        cost = end_time - start_time
        return cost.total_seconds()